import * as crypto from "crypto";
function padding_zero(data: Buffer, is_add: boolean = true) {
    let maxlength = is_add ? (Math.floor(data.length / 8) * 8 + 8) : data.length;
    let temp = new Buffer(maxlength);
    for (let i = 0; i < maxlength; i++) {
        if (i >= data.length) {
            temp.writeUInt8(0, i);
        } else {
            temp.writeUInt8(data[i], i)
        }
    }
    if (is_add == false) {
        while (true) {
            if (temp[maxlength - 1] == 0) {
                maxlength--;
            } else {
                break;
            }
        }
    }
    return temp.slice(0, maxlength);
}
function decodeKey(inputkey: string) {
    let keybuf = new Buffer("1EFDEB7504007654D6D41D35B6E0C0181EFDEB7504007654", "hex")
    var decipher = crypto.createDecipheriv("des-ede3", keybuf, new Buffer(0));
    decipher.setAutoPadding(false)
    var txt = decipher.update(inputkey, 'hex', 'utf8');
    txt += decipher.final('utf8');
    console.log(txt);
    txt = padding_zero(new Buffer(txt, "utf8"), false).toString("utf8")
    return txt;
}
function encodeKey(inputkey: string) {
    let buf = padding_zero(new Buffer(inputkey, "utf8"), true);
    let keybuf = new Buffer("1EFDEB7504007654D6D41D35B6E0C0181EFDEB7504007654", "hex")
    var cipher = crypto.createCipheriv("des-ede3", keybuf, new Buffer(0));
    cipher.setAutoPadding(false)  //default true  
    var ciph = cipher.update(buf, "binary", 'hex');
    ciph += cipher.final('hex');
    console.log(ciph)
    return ciph;
}
function des_encrypt(input: string, key: string) {
    // let _key = key;

    //encrypt  
    let _key = decodeKey(key);
    let buf = padding_zero(new Buffer(input, "utf8"), true);
    let keybuf = new Buffer(_key, "hex")
    var cipher = crypto.createCipheriv("des-ede3", keybuf, new Buffer(0));
    cipher.setAutoPadding(false)  //default true  
    var ciph = cipher.update(buf, "binary", 'hex');
    ciph += cipher.final('hex');
    console.log(ciph)
    return ciph;
    // //decrypt  

}
function des_decrypt(data: string, key: string) {
    // let _key = key;
    let _key = decodeKey(key);
    let keybuf = new Buffer(_key, "hex")
    var decipher = crypto.createDecipheriv("des-ede3", keybuf, new Buffer(0));
    decipher.setAutoPadding(false)
    var txt = decipher.update(data, 'hex', 'utf8');
    txt += decipher.final('utf8');
    console.log(txt);
    txt = padding_zero(new Buffer(txt, "utf8"), false).toString("utf8")
    return txt;
}
function des_initcrypt(data: string, key: string) {
    // let _key = key;
    let realkey = des_decrypt(data, key);
    //真实_key
    return encodeKey(realkey);

}
